﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using StackExchange.Redis;

namespace SignalRTest
{
    public class OnlineUsersHub : Hub
    {
        public async Task Login(string userName)
        {
            // Clients.All.hello();

            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("47.106.207.95:6379,password=123456")) {
                IDatabase db = redis.GetDatabase();
               await db.StringSetAsync("OU_Font_OnlineStatus" + userName, true); //在线状态
                await db.StringSetAsync("OU_Font_UserName" + this.Context.ConnectionId, userName); //保存connectionid与用户名的关系
                //记录登陆过系统的用户名
                await db.SetAddAsync("OU_Font_Users", userName);
                 
            }

            await RefreshOnlineStatus();
        }

        private async Task RefreshOnlineStatus() {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("47.106.207.95:6379,password=123456"))
            {
                IDatabase db = redis.GetDatabase();
                

                RedisValue[] userNames = await db.SetMembersAsync("OU_Font_Users");

                RedisKey[] userNamesOnlineKeys = userNames.Select(un => (RedisKey)("OU_Font_OnlineStatus" + un)).ToArray();
                //批量获取用户在线状态
                var userStatuses = await db.StringGetAsync(userNamesOnlineKeys);

                Dictionary<string, bool> data = new Dictionary<string, bool>();
                for (int i = 0; i < userNames.Length; i++)
                {
                    data[userNames[i]] = (bool)userStatuses[i];
                }

                //通知客户端刷新用户登录状态
                Clients.All.onOnlineUserStatusChange(data);
            }
        }

        public override async Task OnDisconnected(bool stopCalled)
        {
            //return base.OnDisconnected(stopCalled);
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("47.106.207.95:6379,password=123456"))
            {
                IDatabase db = redis.GetDatabase();
               
                string userName = await db.StringGetAsync("OU_Font_UserName"+this.Context.ConnectionId);
                await db.StringSetAsync("OU_Font_OnlineStatus" + userName, false);
            } 

            await RefreshOnlineStatus();
        }
    }
}